/*
 * @lc app=leetcode.cn id=109 lang=cpp
 *
 * [109] 有序链表转换二叉搜索树
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
  TreeNode* sortedListToBST(ListNode* head)
  {
    vector<int> v;
    for (; head; head = head->next)
      v.push_back(head->val);
    return BuildTree(v, 0, v.size() - 1);
  }

  TreeNode* BuildTree(vector<int>& v, int low, int high)
  {
    if (low > high)
      return nullptr;
    int m = low + (high - low) / 2;
    TreeNode* root = new TreeNode(v[m]);
    root->left = BuildTree(v, low, m - 1);
    root->right = BuildTree(v, m + 1, high);
    return root;
  }
};
// @lc code=end
